import { getTokenKey } from "../../utils/auth";
import { getLocationInfo, getDestinationInfo} from "../../utils/location";
import { handleFileUploading, deleteFile } from "../../utils/file.js";
import { deleteMarker, deleteFileFromDbs,uploadInitFile } from "../../utils/user";

const app = getApp();
Page({
  data: {
    markerId: 0,
    current_loc_latitude:'',
    current_loc_longitude:'',
    current_loc_title:'',
    radius: '',
    isUpdate: false,
    description:'',
    imgList:[],
    circleId:0
  },
  onLoad(options){
    if(options.id){
      this.updateInit(options)
    }else{
      getLocationInfo().then(res=>{
        this.setData({
          current_loc_latitude:res.latitude,
          current_loc_longitude:res.longitude,
          current_loc_title: res.title
        })
      }) 
    } 
  },

  updateInit(options){
    console.log(options)
    this.setData({
      isUpdate: true,
      current_loc_latitude: options.latitude,
      current_loc_longitude: options.longitude,
      radius: options.radius,
      description: options.description,
      markerId: options.id,
      current_loc_title: options.title,
      imgList: options.imageList===undefined ? [] : JSON.parse(decodeURIComponent(options.imageList))
    })
  },
  
  chooseImage(e){
    this.setData({
      imgList: e.detail
    })
  },

  // 检查表格是否有错误
  _isFormReady(){
    let isReady = true;
    const children = this.selectAllComponents('.detail-input')
    children.forEach(item=>{
      const isError =item.data.isError
      const value = item.data.value
      if(isError==true || value===''){
        isReady = false
      }
    })
   return isReady
  },

  //提交表格
  async submitForm(){
    var that = this
    if(this._isFormReady()){
      wx.showLoading({
        title: '正在提交',
      })
      this.addBasicInfo().then(res =>{
        if(res.id){
          that.setData({
            circleId: res.id
          })
          that.uploadFiles();
          wx.hideLoading();
          wx.showModal({
            title: '提交成功',
            content:'提交成功',
            success () { 
              wx.switchTab({
                url: '../index/index',
              })
            }
          })   
        }
      })
    }else{
      wx.showModal({
        title: '提交失败',
        content:'信息有误或必要信息未填写！请修正'
      })
    }
  },
  
  //添加圆的基础信息
  addBasicInfo(){
    return new Promise((resolve) => {
      resolve(
        app.call({
          path:'/circle/weChat/add',
          method: 'post',
          header: {
            'X-WX-SERVICE': 'fire-assistant-s',
            'tokens': getTokenKey()//必须添加#######
          },
          data: {
            description: this.data.description,
            latitude: this.data.current_loc_latitude,
            longitude: this.data.current_loc_longitude,
            radius: this.data.radius
          }
        })
      )
    })
    
  },

  uploadFiles(){
    this.data.imgList.forEach((item)=>{
      let filePath = item.tempFilePath
      let name = filePath.substring(filePath.lastIndexOf('/')+1)
      // 在数据库表中上传
      uploadInitFile(app,"circle", item, this.data.circleId).then((res)=>{
        if(res.key){
          // 在对象存储中上传
          handleFileUploading(name, item.tempFilePath, app)
        }else{
          wx.showModal({
            title: '出错了'
          })
        }
      })   
    })
  },

//更新标记
  async updateItem(){
    const itemId = this.data.markerId
    var imgList = this.data.imgList
    if(this._isFormReady()){
      // 更新基本信息
      this.updateBasicInfo(itemId).then(res => {
        // 数据库中已经存储的，但在客户端被更新后删除的， 需要删除之前存在的
        res.files.forEach(item => {
          let count = 0
          imgList.forEach(image =>{
            if(!image.id || item.id !== image.id){
              count++
            }
          })
          if(count === imgList.length){
            // 删除操作 在数据库中删除 
            deleteFileFromDbs(app, "circle", item.id)
            // 删除操作 在cos 中删除
            deleteFile(item, app).then(res=>{
              console.log(res)
            })
          }
        })
        // 添加新图片  在数据库添加和 在对象存储中添加
        imgList.forEach(image =>{
          if(image.tempFilePath){
            let filePath = image.tempFilePath
            let name = filePath.substring(filePath.lastIndexOf('/')+1)
            uploadInitFile(app,"circle", image, itemId).then((res)=>{
              if(res.id){
                handleFileUploading(name, image.tempFilePath, app)
              }
            })
          }
        })
        // 更新成功
        wx.showModal({
          title: '更新成功',
          content: '更新成功',
          complete: () => {
            wx.switchTab({
              url: '../index/index',
            })
          }
        })
      })
    }else {
      wx.showModal({
        title: '填写错误，请重新填写'
      })
    }
  },

  // 更新基本信息
  updateBasicInfo(itemId){
    return new Promise((resolve) => {
      resolve(
        app.call({
          path:`/circle/${itemId}`,
          method: 'put',
          header: {
            'X-WX-SERVICE': 'fire-assistant-s',
            'tokens': getTokenKey()//必须添加#######
          },
          data: {
            latitude: parseFloat(this.data.current_loc_latitude),
            longitude: parseFloat(this.data.current_loc_longitude),
            radius: this.data.radius,
            description: this.data.description
          }
        })
      )
    })
  },

  // 完全删除
  async deleteItem(){
    var imgList = this.data.imgList
    wx.showModal({
      title: '您确定要删除这个消防站吗',
      complete: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '正在删除',
          })
          // 根据markerId删除 数据库中
          deleteMarker(app, "circle", this.data.markerId).then((res)=>{
            if(res){
              wx.showModal({
                title: '出错了',
                content: res.message ? res.message:res
              })
            }else{
              // 删除对象存储中的照片 可能存在问题
              imgList.forEach(item=>{
                if(item.img){
                  // 对象存储中的照片
                  deleteFile(item, app).then(res=>{
                    console.log(res)
                  })
                }
              })
              wx.showModal({
                title: '删除成功',
                complete: () => {
                  wx.hideLoading()
                  wx.switchTab({
                    url: '../index/index',
                  })
                }
              })
            } 
          })
        }
      }
    })
    
  }
 
})